import { getAction, postAction, putAction, deleteAction, downFile } from '@api/manage'
let jsonData = [];


const search = async (configId, fetchData) => {
    let url = `/es/${configId}/_msearch`
    // .then((res) => {
    //     if (res.success) {
    //         const result = getResponses(res.result)
    //         // const result = res.result.json()
    //         console.log(result)
    //         debugger
    //         return result
    //     }
    // })
    const res = await postAction(url, fetchData)
    if (res.success) {
        const result = getResponses(res.result)
        // const result = res.result.json()
        console.log(result)

        return result
    }
}

const getResponses = (res) => {
    const result = JSON.parse(res)
    return result && result.responses && result.responses[0]
}

const getSearchAfterData = async (configId, data, alltotal) => {
    const { hits } = data;
    if (hits && jsonData.length < alltotal) {
        const { hits: totalhits, total } = hits;
        jsonData = jsonData.concat(totalhits);
        const lastObject = totalhits[totalhits.length - 1];
        const nextSearchData = lastObject._id

        return searchAfter(
            configId,
            alltotal,
            nextSearchData
        )
    }

    let str = JSON.stringify(jsonData);

    jsonData = [];
    return str;
}

const searchAfter = async (configId, alltotal, searchAfterData) => {
    const others = {};
    if (searchAfterData) {
        others.search_after = [searchAfterData];
    }
    let fetchData = {
        query: {
            match_all: {},
        },
        size: 1000,
        sort: [{ _id: 'desc' }],
        ...others
    }

    const data = await search(configId, fetchData)

    const res = await getSearchAfterData(configId, data, alltotal)

    if (typeof res === 'string') {
        let exportData = JSON.parse(res);
        const lastObject = exportData[exportData.length - 1];
        exportData = exportData.map(value => {
            const item = Object.assign(value._source);
            item['_id'] = value._id;
            return item;
        });

        return {
            data: exportData,
            searchAfterid: lastObject._id

        };
    }
    return res;
}

export {
    searchAfter
}